package com.ljs.threadpooldemo.controller;

import com.ljs.threadpooldemo.entity.request.ThreadRequest;
import com.ljs.threadpooldemo.service.TestAsynService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@RestController
@Slf4j
public class ReflectController {
    @Resource
    TestAsynService testAsynService;
    @PostMapping("/reflect")
    public void  reflect(){
        /**
         * 可以用反射的方法在分布式事务执行本地方法上使用
         */
        //方法名称
        String methodName="testAsyn";
        ThreadRequest threadRequest=new ThreadRequest();
        threadRequest.setMsg("测试异步");
        //调用本地类的方法
        ReflectionUtils.invokeMethod(getBizMethod(AopContext.currentProxy(), methodName, threadRequest), AopContext.currentProxy(), threadRequest);
    }
    private static Method getBizMethod(Object serviceProxy, String methodName, Object... args) {
        log.debug(">>>>>>>>>>>>>>>>>========{}-{}-{}", serviceProxy.getClass(), methodName, args.length);
        //TODO 增加缓存Class提升性能
        Class<?>[] paramTypes = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            paramTypes[i] = args[i].getClass();
        }
        return ReflectionUtils.findMethod(serviceProxy.getClass(), methodName, paramTypes);
    }
    public void testAsyn(ThreadRequest threadRequest){
        System.out.println("我准备调用异步方法"+Thread.currentThread().getName());
        testAsynService.testAsyn();
    }
}
